<?php

/**
 * Created by PhpStorm.
 * User: songs
 * Date: 2019/10/15
 * Time: 9:24
 */

namespace App\Services\Api;

use App\admin\Service\OA;
use App\Jobs\Fun;
use App\Models\Admin\OrderBaleModel;
use App\Models\Admin\OrderCheckModel;
use App\Models\Admin\OrderTempModel;
use App\Models\LogModel;
use App\Models\OrderCommentModel;
use App\Models\User\UserLevelModel;
use App\Services\OrdersPayService;
use Illuminate\Http\Request;
use App\Models\MoneyBilModel;
use DB;
use App\Models\User\UserOrdersModel;

/// App\Services\Api\Order@
class Order extends ApiBase
{

    /**
     * 用于生成订单

    public function GeneratePayOrder(Request $request)
    {
        $baleID = $request['bale'];

        $notes = '';

        $uid = OA::$user->getId();

       ///  先判断是否允许购买

        $OrderBale = OrderBaleModel::where(['id' => $baleID])->first();
        if (!$OrderBale) {
            OA::Json(1, '订单不存在');
        }
        if ($OrderBale->status !== OrderBaleModel::status_kaishi) {
            OA::Json(1, '暂时不能抢单');
        }
        if ($OrderBale->period < time()) {
            OA::Json(1, '已经超过了截止时间');
        }
        $myLevelinfo=UserLevelModel::getUserLevel($uid);
        $myLevel=$myLevelinfo['type'];
        $yaoqiuLevel=$OrderBale->level;
        if($yaoqiuLevel>$myLevel){
            OA::Json(1, '该订单要求'.UserLevelModel::getLevelInfo($yaoqiuLevel)['name'].'等级以上,请提升信用等级');
        }
       // var_dump($yaoqiuLevel,$myLevel);exit;


       //自己是否已经下单,


        $one = OrderTempModel::where([
            'bale' => $request['bale'],
            'fid' => $uid,
          //  'play_status'=>OrderTempModel::play_status_zhifu
            // 'play_status'=>OrderTempModel::play_status_weizhifu
        ])->select('id', 'uid', 'status', 'out_trade_no')->first();
        if ($one) {
        //    if ($one->play_status == OrderTempModel::play_status_zhifu) {
                OA::Json(0, [
                  ///  'play_status' => $one['play_status'],
                    //  'status'=>$one['status'],
                    'out_trade_no' => $one['out_trade_no'],
                   /// 'money' => $one['bond_money'],
                ]);
        }


        $out_trade_no = date('Ymdhms') . mt_rand(1000, 9999);

        $saveOn = $this->orderTempAdd([
            'bale' => $baleID,
            'cid' => $OrderBale['uid'],
            'fid' => $uid,
            'out_trade_no' => $out_trade_no,
            'status' => OrderTempModel::status_qiangdanzhong,
            'created_at' => time(),
            'updated_at' => time(),
        //    'bond_money' => $OrderBale['bond'],
            'notes' => $notes
        ]);
        if (!$saveOn) {
            OA::Json(1, '暂时不能抢单,请稍候再试 ');
        }
        OA::Json(0, [
            ///'play_status'=>$one['play_status'],
         //   'play_status' => $saveOn['play_status'],
            'out_trade_no' => $saveOn['out_trade_no'],
         //   'money' => $saveOn['bond_money'],
        ]);
    }*/

    /**
     * 插入抢单信息表
     * @param $oid
     */
    private function orderTempAdd($data = [])
    {
        if (!$data) {
            return false;
        }
        $newOrder = new OrderTempModel();
        $newOrder->bale = $data['bale'];
        $newOrder->fid = $data['fid'];
        $newOrder->cid = $data['cid'];
        $newOrder->status = $data['status'];
        $newOrder->notes = $data['notes'];
        $newOrder->out_trade_no = $data['out_trade_no'];
        $newOrder->created_at = time();
        $newOrder->updated_at = time();
  ///      $newOrder->play_status = OrderTempModel::play_status_weizhifu;
        $newOrder->f_level = $data['f_level'];
        $newOrder->ip = Fun::Ip();
        $newOrder->ua = Fun::UA();
        $newOrder->uid = OA::$user->getId();
        if ($newOrder->save()) {
            return $newOrder;
        } else {
            return false;
        }
    }

    /*     * 生成支付链接


    private function GeneratePayHref($request)
    {
        OA::Json(1, '不再使用');
        $channel = strtolower($request->input('channel', 'm'));

        $playType = $request->input('playType', 'alipay');
        $uid = OA::$user->getId();
        $out_trade_no = $request->input('out_trade_no', '');
        /// var_dump($playType,$uid,$out_trade_no);

        if ($playType !== OrdersPayService::play_alipay) {
            OA::Json(1, '目前只支持支付宝支付');
        }
        $orderTemp = OrderTempModel::where([
            'out_trade_no' => $out_trade_no,
            'uid' => $uid
        ])->where('created_at', '>', time() - OrderTempModel::MaxTime)
            ->select('id', 'uid', 'play_status', 'status', 'out_trade_no', 'money', 'bale')->first();
        if (!$orderTemp) {
            OA::Json(1, '订单不存在,或者已经失效,请返回重新抢单');
        }

        if ($orderTemp->play_status != OrderTempModel::play_status_weizhifu) {
            OA::Json(1, '订单不是未支付状态');
        }
        $orderBale = OrderBaleModel::where('id', $orderTemp['bale'])->first();
        // var_dump($orderTemp['bale'],$orderTemp);exit;
        if (!$orderBale) {
            OA::Json(1, '抢单不存在,请重新下单');
        }
        if ($orderBale['status'] !== OrderBaleModel::status_kaishi) {
            OA::Json(1, '抢单错误,请重新下单');
        }
        $subject = str_replace('&#8226;', '·', $orderBale['name']);

        $payMode = $request->input('payMode', 'directpay');
        $orderPayService = new OrdersPayService();


        $result = $orderPayService->createaAipayTrade($channel, $payMode, [
            'oid' => $orderBale['id'] ?? 0,
            'out_trade_no' => $orderTemp['out_trade_no'] ?? '', //支付宝交易号
            'subject' => $subject,
            'money' => $orderTemp['money'] ?? 0, //交易费用
            'body' => '抢单保证金', //费用描述
            'notifyUrl' => route('pay.alipay.notify'),
            'returnUrl' => route('pay.alipay.success')
        ]);
        if ($result === false) {
            OA::Json(1, '系统错误,请重试');
        }
        OA::Json(0, ['href' => $result]);
    }*/

    /**
     * 立刻抢单,如果符合等级,生成订单,如果不符合返回错误提示

    public function ConfirmPayOrder($request)
    {
        $notes = $request['notes'] ?? '';
        if (strlen($notes) >= 512) {
            OA::Json(1, '备注不能太多');
        }

        $baleID = $request['id'];
        $uid = OA::$user->getId();

        ///  先判断是否允许购买

        $OrderBale = OrderBaleModel::where(['id' => $baleID])->first();
        if (!$OrderBale) {
            OA::Json(1, '订单不存在');
        }
        if ($OrderBale->status !== OrderBaleModel::status_kaishi) {
            OA::Json(1, '暂时不能抢单');
        }
        if ($OrderBale->period < time()) {
            OA::Json(1, '已经超过了截止时间');
        }
        $myLevelinfo=UserLevelModel::getUserLevel($uid);
        $myLevel=$myLevelinfo['type'];
        $yaoqiuLevel=$OrderBale->level;
        if($yaoqiuLevel>$myLevel){
            OA::Json(1, '该订单要求'.UserLevelModel::getLevelInfo($yaoqiuLevel)['name'].'等级以上,请提升信用等级');
        }
        // var_dump($yaoqiuLevel,$myLevel);exit;


        //自己是否已经下单,


        $one = OrderTempModel::where([
            'bale' =>$baleID,
            'fid' => $uid,
            //  'play_status'=>OrderTempModel::play_status_zhifu
            // 'play_status'=>OrderTempModel::play_status_weizhifu
        ])->select('id', 'uid', 'status', 'out_trade_no')->first();
        if ($one) {
            $one->notes=$notes;
            $one->save();

            OA::Json(0, [
                'out_trade_no' => $one['out_trade_no']
            ]);
        }


        $out_trade_no = date('Ymdhms') . mt_rand(1000, 9999);
        $f_level=0;
        $level=\App\Models\User\UserLevelModel::getUserLevel($uid);
        if($level){
            $f_level= $level['type'];
        }

        $saveOn = $this->orderTempAdd([
            'bale' => $baleID,
            'cid' => $OrderBale['uid'],
            'fid' => $uid,
            'out_trade_no' => $out_trade_no,
            'status' => OrderTempModel::status_qiangdanzhong,
            'created_at' => time(),
            'updated_at' => time(),
               'f_level' => $f_level,
            'notes' => $notes
        ]);
        if (!$saveOn) {
            OA::Json(1, '暂时不能抢单,请稍候再试 ');
        }
        OA::Json(0, [
            'out_trade_no' => $saveOn['out_trade_no']
        ]);






        / *
               /// $out_trade_no = $request->input('out_trade_no', '');
                /// var_dump($playType,$uid,$out_trade_no);
                $orderTemp = OrderTempModel::where([
                    'out_trade_no' => $out_trade_no,
                    'uid' => OA::$user->getId()
                ])->where('created_at', '>', time() - OrderTempModel::MaxTime)
                    ->select('id', 'uid', 'play_status', 'status', 'out_trade_no', 'bond_money', 'bale', 'fid')->first();
                if (!$orderTemp) {
                    OA::Json(1, '订单不存在,或者已经失效,请返回重新抢单');
                }
                $orderTemp->notes = $notes;
                if ($orderTemp->play_status != OrderTempModel::play_status_weizhifu) {
                    OA::Json(1, '您已经抢过该订单了');
                }

                if ($orderTemp->status != OrderTempModel::status_weizhifu) {
                    OA::Json(1, '您已经抢过该订单了');
                }

                if ($this->jqMoney($orderTemp)) {
                    OA::Json(0, ['out_trade_no' => $out_trade_no]);
                } else {
                    \App\Models\LogModel::add($this->msgerror . ',order:' . $out_trade_no);
                    OA::Json(1, $this->msgerror);
                }
        * /
    }*/

    private $msgerror = '';

    private function jqMoney(OrderTempModel &$orderTemp)
    {

        $uid = OA::$user->getId();
        try {
            DB::beginTransaction();
            if($orderTemp->bond_money>0){
                $zhuanchu=MoneyBilModel::zhuanzhangAtoB($uid, MoneyBilModel::system_uid, $orderTemp->bond_money, '为抢' . $orderTemp->out_trade_no . '订单支付');
                $orderTemp->play_no = $zhuanchu;
            }else{
                $orderTemp->play_no='';
            }

            $orderTemp->status = OrderTempModel::status_qiangdanzhong;
            $orderTemp->play_status = OrderTempModel::play_status_zhifu;

            if (!$orderTemp->save()) {
                $this->msgerror = '更新订单错误';
                DB::rollback();
                return false;
            }

            DB::commit();
            return true;
        } catch (\Exception $e) {
            $this->msgerror = $e->getMessage();
            DB::rollback();
            return false;
        }
    }

    /**
     * 为用户充值
     */
    public function GenchongzhiPayHref(Request $request)
    {
        $playtype = $request->get('playtype');
        $money = $request->get('value');
        $res = MoneyBilModel::GenChongzhiOrder(MoneyBilModel::PlayType_zhifubao, $money);
        OA::Json(0, $res);
    }

    /**
     * 生成用户提现订单
     */
    public function tixian(Request $request)
    {
        $orderOn = MoneyBilModel::GenTixian($request->input('tixianmoney'), $request->input('xingming'), $request->input('zhifubao'));
        OA::Json(0, $orderOn);
    }

    /**
     * 修改订单为抢单成功状态
     * @deprecated
     * /
    private function xuanzehezuo(Request $request)
    {
        OA::Json(1111,'需要调整下');
        $out_trade_no=$request->input('out_trade_no');
        $orderTemp = OrderTempModel::where([
            'out_trade_no' => $out_trade_no,
            'cid' => OA::$user->getid()
        ])->first();
        if (!$orderTemp) {
            OA::Json(1, '订单不存在,或者无权限');
        }
        $orderTemp->status = OrderTempModel::status_wancheng;
        $orderBale = OrderBaleModel::where([
            'id' => $orderTemp->bale,
            'uid' => OA::$user->getid()
        ])->first();
        if (!$orderBale) {
            OA::Json(1, '订单不存在,或者无权限');
        }
        $orderBale->status = OrderBaleModel::status_wancheng;
        $orderBale->updated_at = time();


        /**
         * 查找未选择的工厂,返还他们的保证金
        * /
        $noSelectList=OrderTempModel::where([
            'bale'=>$orderTemp->bale,
            'play_status'=>OrderTempModel::play_status_zhifu
        ])
            ->where('out_trade_no','!=',$out_trade_no)
            ->select(['bale','out_trade_no','id','bale','status','bond_money','fid'])
            ->get();
       // print_r($noSelectList);exit;

        try {
            DB::beginTransaction();
            if (!$orderTemp->save()) {
                DB::rollback();
                OA::Json(1, '修改下单错误');
            }
            if (!$orderBale->save()) {
                DB::rollback();
                OA::Json(1, '修改发布订单错误');
            }
            $UserOrdersModele = new UserOrdersModel;
            $UserOrdersModele->order_no = $orderTemp->out_trade_no;
            $UserOrdersModele->bale = $orderTemp->bale;
            $UserOrdersModele->temp = $orderTemp->id;
            $UserOrdersModele->cid = $orderTemp->cid;
            $UserOrdersModele->fid = $orderTemp->fid;
            $UserOrdersModele->num = $orderBale->num;
            $UserOrdersModele->money = $orderBale->money;
            $UserOrdersModele->bond_money = $orderTemp->bond_money;
            $UserOrdersModele->kd_name = '';
            $UserOrdersModele->kd_code = '';
            $UserOrdersModele->kd_time = 0;
            $UserOrdersModele->status = UserOrdersModel::status_weifayuanliao;
            $UserOrdersModele->note = $orderTemp->notes;
            $UserOrdersModele->other = '';
            $UserOrdersModele->created_at = time();
            $UserOrdersModele->updated_at = time();
            if (!$UserOrdersModele->save()) {
                DB::rollback();
                OA::Json(1, '修改错误,创建订单错误');
            }

            $this->tuihuan($noSelectList);

            DB::commit();
            OA::Json(0, 'ok');
        } catch (\Exception $e) {
            $this->msgerror = $e->getMessage();
            DB::rollback();
            OA::Json(1, '事务处理错误' . $this->msgerror);
        }


        OA::Json(0, 'ok');
    } */


    /**
     * 保证金的退还
    */
    private function tuihuan(&$list){
        foreach ($list as $vo){
             MoneyBilModel::zhuanzhangAtoB(MoneyBilModel::system_uid,$vo['fid'],$vo['bond_money'],
            '订单号:'.$vo['out_trade_no'].',抢单失败,保证金返还');
            $vo->status=OrderTempModel::status_fail;
            if(!$vo->save()){
                throw new \Exception('订单状态设置错误');
            }
        }
    }

    /**
     * 保存公司发过来的清单
     */
    public function send_yuanliao(Request $request)
    {
        $users_orders = UserOrdersModel::where([
            'order_no' => $request->input('out_trade_no'),
            'cid' => OA::$user->getId()
        ])->first();
        if (!$users_orders) {
            OA::Json(1, '订单不存在,或者无权限');
        }
        if ($users_orders->yuanliao_time != 0) {
            OA::Json(1, '系统错误,原料已经发给工厂,无法再次修改');
        }
        ///var_dump($request->input('data.array'),$request->input('data.public'));exit;
        $users_orders->yuanliao = json_encode($request->input('data.array'));
        if($users_orders->status==UserOrdersModel::status_weifayuanliao){
            $users_orders->status=UserOrdersModel::status_jieshouyuanliao;
        }

        if ($request->input('data.public') == 'true') {
            $users_orders->yuanliao_time = time();
        }
        if ($users_orders->save()) {
            OA::Json(0);
        } else {
            OA::Json(1, '系统错误,请重试');
        }

    }


    /**
     * 创建跟单验收记录,以及所属的用户, 参数:out_trade_no,check_type="cid|fid" cid表示公司 fid表示工厂
     */
    public function comCheckUid(Request $request)
    {
        $out_trade_no = $request['out_trade_no'] ?? '';
        if ($out_trade_no == '') {
            Fun::showmsg("参数错误");
        }
        $check_type = $request['check_type'] ?? '';
        if ($check_type !== 'cid' && $check_type !== 'fid') {
            Fun::showmsg("参数错误");
        }
        $orderTempModel = OrderTempModel::where(['out_trade_no' => $out_trade_no])->first();
        if (!$orderTempModel) {
            Fun::showmsg("订单不存在");
        }
        $uid = OA::$user->getId();
        if ($orderTempModel->cid != $uid) {
            Fun::showmsg("没有修改的权限");
        }
        $ordercheck = OrderCheckModel::where(['out_trade_no' => $out_trade_no])->first();
        if ($ordercheck) {
            Fun::showmsg("跟单验货报告已经设置过所属权限,无法再次修改");
        }
        $ordercheck = new OrderCheckModel;
        $ordercheck->out_trade_no = $out_trade_no;
        $ordercheck->stylelist = '';
        $ordercheck->sizelist = '';
        $ordercheck->thrumlist = '';
        $ordercheck->detail = '';
        $ordercheck->staffTotalNum = 0;
        $ordercheck->staffStyleNum = 0;
        $ordercheck->del = 0;
        $ordercheck->created_at = time();
        $ordercheck->updated_at = time();
        $ordercheck->other_stylelist = 0;
        $ordercheck->other_sizelist = '';
        $ordercheck->other_thrumlist = '';
        $ordercheck->com_name = '';
        $ordercheck->com_tel = '';
        if ($check_type == 'fid') {
            $ordercheck->check_uid = $orderTempModel->fid;
        } elseif ($check_type == 'cid') {
            $ordercheck->check_uid = $orderTempModel->cid;
        } else {
            Fun::showmsg("参数错误");
        }
        $save = $ordercheck->save();
        if ($save) {
            OA::Json(0);
        } else {
            OA::Json(1, '系统错误,请重试');
        }

    }

    public function savecomCheck(Request $request)
    {
        $out_trade_no = $request['out_trade_no'] ?? '';
        if ($out_trade_no == '') {
            Fun::showmsg("参数错误");
        }

        $ordercheck = OrderCheckModel::where([
            'out_trade_no' => $out_trade_no,
            'check_uid'=>OA::$user->getId()
        ])->first();
        if (!$ordercheck) {
            Fun::showmsg("验货单不存在,或者权限不允许");
        }
     //   var_dump($request->input('stylelist'));exit;

        $ordercheck->stylelist=json_encode($request->input('stylelist'));
        $ordercheck->sizelist=json_encode($request->input('sizelist'));
        $ordercheck->thrumlist=json_encode($request->input('thrumlist'));

        $ordercheck->detail=Fun::encode($request->input('detail'));
        $ordercheck->staffTotalNum=Fun::encode($request->input('staffTotalNum'));
        $ordercheck->staffStyleNum=Fun::encode($request->input('staffStyleNum'));
        $ordercheck->finishTime=strtotime($request->input('finishTime'));

        $ordercheck->com_name=Fun::encode($request->input('com_name'));
        $ordercheck->com_tel=Fun::encode($request->input('com_tel'));
        $ordercheck->updated_at = time();
        if($ordercheck->save()){
            OA::Json(0);
        } else {
            OA::Json(1, '系统错误,请重试');
        }
    }


    public function order_fabuo(Request $request){
        $out_trade_no = $request['out_trade_no'] ?? '';
        if ($out_trade_no == '') {
            Fun::showmsg("参数错误");
        }
        $users_orders = UserOrdersModel::where([
            'order_no' =>$out_trade_no,
            'fid' => OA::$user->getId()
        ])->first();
        if (!$users_orders) {
            OA::Json(1, '订单不存在,或者无权限');
        }
        $users_orders->receiving_address=$request->input('receiving_address');
        $users_orders->send_address=$request->input('send_address');
        $users_orders->kd_name=$request->input('kd_name');
        $users_orders->kd_code=$request->input('kd_code');
        $users_orders->kd_time=time();
        $users_orders->status=UserOrdersModel::status_dabaofahuo;
        if($users_orders->save()){
            OA::Json(200);
        }else{
            OA::Json(1, '系统错误,请重试');
        }
    }

    /**
     *  确认收货
     */
    public function querenshouhuo(Request $request){
        $out_trade_no = $request['out_trade_no'] ?? '';
        if ($out_trade_no == '') {
            Fun::showmsg("参数错误");
        }
        $users_orders = UserOrdersModel::where([
            'order_no' =>$out_trade_no,
            'cid' => OA::$user->getId()
        ])->first();
        if (!$users_orders) {
            OA::Json(1, '订单不存在,或者无权限');
        }
        $users_orders->status=UserOrdersModel::status_daohuoqianshou;
        if($users_orders->save()){
            OA::Json(0);
        }else{
            OA::Json(1, '系统错误,请重试');
        }
    }

    /**
     * 设置开始生产的状态
     */
    public function Kaishishengchan(Request $request){
        $out_trade_no = $request['out_trade_no'] ?? '';
        if ($out_trade_no == '') {
            Fun::showmsg("参数错误");
        }
        $users_orders = UserOrdersModel::where([
            'order_no' =>$out_trade_no,
            'fid' => OA::$user->getId()
        ])->first();
        if (!$users_orders) {
            OA::Json(1, '订单不存在,或者无权限');
        }
        $users_orders->status=UserOrdersModel::status_shengchanzhong;
        if($users_orders->save()){
            OA::Json(0);
        }else{
            OA::Json(1, '系统错误,请重试');
        }
    }

    /**
     * 设置订单为完成状态,返回保证金
    */
   /* public function orderwancheng(Request $request){
        $out_trade_no = $request['out_trade_no'] ?? '';
        if ($out_trade_no == '') {
            Fun::showmsg("参数错误");
        }
        $users_orders = UserOrdersModel::where([
            'order_no' =>$out_trade_no,
            'cid' => OA::$user->getId()
        ])->first();
        if (!$users_orders) {
            OA::Json(1, '订单不存在,或者无权限');
        }
        if($users_orders->status==UserOrdersModel::status_wancheng){
            OA::Json(1, '订单已经设置过了,无法再次设置');
        }

        if($users_orders->bond_money==0){
            $users_orders->status=UserOrdersModel::status_wancheng;
            if($users_orders->save()){
                OA::Json(0);
            }
        }

        try {
            DB::beginTransaction();
            $users_orders->status=UserOrdersModel::status_wancheng;
            MoneyBilModel::zhuanzhangAtoB(MoneyBilModel::system_uid,$users_orders->fid,$users_orders->bond_money,
                '订单号:'.$users_orders->order_no.'保证金返还');
            if(!$users_orders->save()){
                //OA::Json(0);
                throw new \Exception('订单状态保存错误');
            }
           //

            DB::commit();
            OA::Json(0);

        } catch (\Exception $e) {
            DB::rollback();
            \Log::error($e->getMessage());
            LogModel::add($e->getMessage(),LogModel::typeError);
            OA::Json(1, '设置错误,请联系管理员');
        }

    }*/




}
